#!/bin/bash

# Frontend Deployment Script - Bash Version
# Usage: ./deploy-full.sh [environment] [ssh_key_path]
# Parameters:
#   environment: dev|sit|prod|odev|oprod (default: dev)
#   ssh_key_path: SSH private key path (default: ~/.ssh/id_rsa if exists)

# 1. 本地构建
echo "[1/4] Building frontend project..."
npm install && npm run build
if [ $? -ne 0 ]; then
    echo "Frontend build failed, deployment terminated."
    exit 1
fi

# 获取参数
ENV_ARG=$1
SSH_KEY_PATH=$2

if [ -z "$ENV_ARG" ]; then
  ENV_ARG=dev
fi

# 如果没有提供SSH密钥路径，尝试使用默认密钥
if [ -z "$SSH_KEY_PATH" ]; then
    SSH_KEY_PATH="$HOME/.ssh/id_rsa"
fi

echo "=============== Frontend Deployment Config ==============="
echo "Environment: $ENV_ARG"
if [ -n "$SSH_KEY_PATH" ] && [ -f "$SSH_KEY_PATH" ]; then
    echo "SSH Key: $SSH_KEY_PATH"
    echo "Authentication: SSH Key (passwordless)"
else
    echo "SSH Key: Not provided or not found"
    echo "Authentication: Password"
fi
echo "=========================================================="
echo ""

# 根据环境选择服务器
case $ENV_ARG in
  dev|sit|prod)
    # 服务器一
    PASSWORD="Qinxiao#12345"
    REMOTE_USER="appadmin"
    REMOTE_HOST="168.61.74.34"
    REMOTE_DIR="/home/appadmin/app/web"
    NGINX_PORT=13000
    echo "使用服务器一部署环境: $ENV_ARG"
    ;;
  odev|oprod)
    # 服务器二（当前配置）
    PASSWORD="Sunny1234"
    REMOTE_USER="appadmin"
    REMOTE_HOST="115.159.214.105"
    REMOTE_DIR="/home/appadmin/app/web"
    NGINX_PORT=13000
    echo "使用服务器二部署环境: $ENV_ARG"
    ;;
  *)
    echo "不支持的环境: $ENV_ARG，支持的环境: dev, sit, prod, odev, oprod"
    exit 1
    ;;
esac

# 2. 创建部署包
echo "[2/4] Creating deployment package..."
cd build || { echo "build directory does not exist"; exit 1; }
ZIP_FILE="code-knowledge-web-$(date +%Y%m%d%H%M%S).zip"
zip -r "$ZIP_FILE" ./*
if [ $? -ne 0 ]; then
    echo "Failed to create deployment package"
    exit 1
fi
cd ..

# 3. 上传部署包到服务器
echo "[3/4] Uploading deployment package..."
if [ -n "$SSH_KEY_PATH" ] && [ -f "$SSH_KEY_PATH" ]; then
    echo "使用SSH密钥认证上传..."
    scp -i "$SSH_KEY_PATH" "build/$ZIP_FILE" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"
else
    echo "使用密码认证上传，请输入服务器密码: $PASSWORD"
    scp "build/$ZIP_FILE" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"
fi
if [ $? -ne 0 ]; then
  echo "上传部署包失败"
  exit 1
fi
echo "上传完成"

ZIP_BASENAME=$(basename "build/$ZIP_FILE")

# 4. 远程部署：清理旧文件，解压新包
echo "[4/4] Remote deployment..."
if [ -n "$SSH_KEY_PATH" ] && [ -f "$SSH_KEY_PATH" ]; then
    echo "使用SSH密钥认证执行远程部署..."
    ssh -i "$SSH_KEY_PATH" "$REMOTE_USER@$REMOTE_HOST" "
        cd $REMOTE_DIR
        echo 'Step 1: Backing up current deployment...'
        if [ -d 'static' ]; then
            mv static static_backup_\$(date +%Y%m%d%H%M%S) || true
        fi
        
        echo 'Step 2: Extracting new deployment package...'
        unzip -o '$ZIP_BASENAME'
        
        echo 'Step 3: Cleaning up deployment package...'
        rm -f '$ZIP_BASENAME'
        
        echo 'Step 4: Deployment verification...'
        if [ -f 'index.html' ]; then
            echo 'Frontend deployment completed successfully!'
        else
            echo 'Frontend deployment may have failed - index.html not found'
            exit 1
        fi
    "
else
    echo "使用密码认证执行远程部署，请再次输入服务器密码: $PASSWORD"
    ssh "$REMOTE_USER@$REMOTE_HOST" "
        cd $REMOTE_DIR
        echo 'Step 1: Backing up current deployment...'
        if [ -d 'static' ]; then
            mv static static_backup_\$(date +%Y%m%d%H%M%S) || true
        fi
        
        echo 'Step 2: Extracting new deployment package...'
        unzip -o '$ZIP_BASENAME'
        
        echo 'Step 3: Cleaning up deployment package...'
        rm -f '$ZIP_BASENAME'
        
        echo 'Step 4: Deployment verification...'
        if [ -f 'index.html' ]; then
            echo 'Frontend deployment completed successfully!'
        else
            echo 'Frontend deployment may have failed - index.html not found'
            exit 1
        fi
    "
fi

if [ $? -ne 0 ]; then
    echo "远程部署失败"
    exit 1
fi

echo ""
echo "Frontend deployment completed!"
echo "Application URL: http://${REMOTE_HOST}:${NGINX_PORT}"
echo "Deploy Directory: $REMOTE_DIR"
echo "Environment: $ENV_ARG"